package com.voice.server.connection;

import com.voice.core.channel.IOContext;
import com.voice.core.channel.tcp.impl.IOSelectorConnectionManager;
import com.voice.core.connection.ConnectionManager;
import com.voice.core.connection.entity.StreamData;
import com.voice.server.connection.map.DeviceControllerConnectionMap;
import com.voice.server.connection.map.SdkConnectionMap;
import com.voice.server.enums.PushTypeEnum;
import com.voice.server.message.device.ServerMessage;
import com.voice.server.properties.ServerProperties;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.CompletableFuture;


public class ConnectionInvoke extends IOSelectorConnectionManager implements ConnectionManager {

    public ConnectionInvoke(IOContext ioContext) {
        super(ioContext);
    }

    @Autowired
    private SdkConnectionMap sdkConnectionMap;
    @Autowired
    private DeviceControllerConnectionMap deviceControllerConnectionMap;
    @Autowired
    private ServerProperties serverProperties;

    public CompletableFuture<StreamData> sendSdkMessage(String userId, String topic, Object data){
        return sdkConnectionMap.sendMessage(userId,topic,data);
    }

    public CompletableFuture<StreamData> sendSdkMessage(String userId, String topic,int qos,Object data){
        return sdkConnectionMap.sendMessage(userId,topic,qos,data);
    }

    public CompletableFuture<StreamData> sendDeviceMessage(String deviceKey, String topic,Object data){
        return deviceControllerConnectionMap.sendMessage(deviceKey,topic,data);
    }

    public CompletableFuture<StreamData> sendDeviceMessage(String deviceKey, String topic,int qos,Object data){
        return deviceControllerConnectionMap.sendMessage(deviceKey,topic,qos,data);
    }

    public void sendServerMessageToDevice(String userId,String deviceKey,int pushType){
        ServerMessage serverMessage;
        if (pushType == PushTypeEnum.Bytes.getCode()) {
            SdkConnection sdkConnection = sdkConnectionMap.get(userId);
            if(sdkConnection!=null&&sdkConnection.getHost()!=null&&sdkConnection.getPort()!=null){
                serverMessage=new ServerMessage(sdkConnection.getHost(),sdkConnection.getPort());
                this.sendDeviceMessage(deviceKey,"/device/server",serverMessage);
                return;
            }
        }
        serverMessage = new ServerMessage(serverProperties.getHost(), serverProperties.getPort());
        this.sendDeviceMessage(deviceKey, "/device/server", serverMessage);
    }

}
